import React, { Component } from "react";
import { NavBar, Toast } from "antd-mobile";
import { withRouter } from "react-router-dom";
import { imgURL } from "../../baseURL/baseURL";
import { getCartData, updateCart, deleteCartGoods } from "../../data/apiLiao";
import styles from "./Cart.module.scss";
class Cart extends Component {
  state = {
    // 购物车数据
    data: [],
    // 未编辑状态
    isEdit: false,
    // 是否全选
    isChoiceAll: false,
    // 判断是否有商品被选中
    ischecked: false,
    // 选中的商品个数
    num: 0,
    // 购物车是否有商品
    product: true
  };
  componentDidMount() {
    let token = localStorage.getItem("token");
    if (token) {
      this.getCart();
    }
  }
  getCart = async () => {
    let resCart = await getCartData();
    if (resCart.success) {
      // 如果原来就有数据，把原来的选中状态赋给新数据
      if (this.state.data.length !== 0) {
        resCart.data.forEach((v) => {
          let status = false;
          this.state.data.forEach((i) => {
            if (i.id === v.id) {
              status = i.checked;
            }
          });
          v.checked = status;
        });
      } else {
        resCart.data.forEach((v) => {
          v.checked = false;
        });
      }
      // 如果没有商品
      if(resCart.data.length === 0){
        this.setState({
          product: false
        });
      }
      this.setState({
        data: resCart.data,
      },()=>{
        this.changeStatus();
      });
    }
  };
  // 编辑按钮，点击编辑购物车
  handlerEdit = () => {
    if (this.state.isEdit) {
      this.setState({
        isEdit: false,
      });
    } else {
      this.setState({
        isEdit: true,
      });
    }
  };
  // 跳转到登录页
  toLogin = () => {
    this.props.history.push("login");
  };
  // 去逛逛，跳转到首页
  toHome = () => {
    this.props.history.push("home");
  };
  // 删除选中商品
  deleteGoods = async () => {
    // 把选中的商品id遍历出来放在一个数组中
    let data = [];
    this.state.data.forEach((v) => {
      if (v.checked) {
        data.push(v.id);
      }
    });
    if (data.length) {
      let res = await deleteCartGoods(data);
      if (res.success) {
        this.getCart();
      }
    }
  };
  // 结算选中商品
  settleAccounts = () => {
    // 把选中的商品遍历出来，
    let data = "";
    let i = 1;
    this.state.data.forEach((v) => {
      if (v.checked && this.state.num !== i) {
        i += 1;
        data += "ids=" + v.id + "&";
      } else if (v.checked && this.state.num === i) {
        data += "ids=" + v.id;
      }
    });
    if (data.length) {
      this.props.history.push("checkout?" + data);
    }
  };
  // 点击选择商品
  handlerChoice = (params) => {
    this.setState(
      (preState) => {
        preState.data[params.i].checked = !preState.data[params.i].checked;
        return {
          data: preState.data,
        };
      },
      () => {
        this.changeStatus();
      }
    );
  };
  // 修改状态
  changeStatus = () => {
    // 判断所有商品是否全选
    let flag = true;
    // 判断是否有商品被选中
    let thing = false;
    // 选中商品个数
    let j = 0;
    this.state.data.forEach((v) => {
      if (!v.checked) {
        flag = false;
      } else if (v.checked) {
        thing = true;
        j += 1;
      }
    });
    // 有商品选中的
    this.setState({
      ischecked: thing,
    });
    // 选中个数
    this.setState({
      num: j,
    });
    // 全选
    this.setState({
      isChoiceAll: flag,
    });
  }
  
  // 点击全选按钮
  handlerChoiceAll = () => {
    let flag = this.state.isChoiceAll;
    // 取反
    this.setState((preState) => {
      preState.data.forEach((v) => {
        v.checked = !flag;
      });
      return {
        data: preState.data,
      };
    });
    this.setState({
      isChoiceAll: !flag,
    });
    this.setState({
      ischecked: !flag,
    });
    if (!flag) {
      this.setState({
        num: this.state.data.length,
      });
    } else {
      this.setState({
        num: 0,
      });
    }
  };
  // 购物车商品数量加按钮
  cartAdd = async (params) => {
    params.count += 1;
    let res = await updateCart(params);
    if (res.success) {
      this.getCart();
    }
  };
  // 购物车商品数量减按钮
  cartSub = async (params) => {
    if (params.count <= 1) {
      Toast.info("不能再减少了", 1);
    } else {
      params.count -= 1;
      let res = await updateCart(params);
      if (res.success) {
        this.getCart();
      }
    }
  };
  // 跳转到商品详情页
  handlerToDetail = (id) => {
    this.props.history.push("goodsDetail?"+id);
  }
  
  render() {
    // 判断是否登录
    let token = localStorage.getItem("token");
    let sum = 0;
    if (this.state.data && this.state.data.length !== 0) {
      this.state.data.forEach((v) => {
        if (v.checked) {
          sum += (v.price * v.count) / 100;
        }
      });
    }
    return (
      <div className={styles.shopCart}>
        {/* 顶部导航栏开始 */}
        <div className={styles.cartHead}>
          <NavBar
            mode="light"
            rightContent={[
              <div
                className={styles.editor}
                key="edit"
                onClick={this.handlerEdit}
              >
                {this.state.isEdit ? "完成" : "编辑"}
              </div>,
            ]}
          >
            购物车
          </NavBar>
        </div>
        {/* 顶部导航栏结束 */}
        {/* 购物车内容开始 */}
        <div className={styles.cartBody}>
          {/* 未登录状态开始 */}
          {!token ? (
            <div className={styles.cartNotLogin}>
              <div className={styles.notLoginIcon}>
                <i className={styles.iconStyle + " iconfont icon-gouwuche"}></i>
                <div className={styles.text}>还没有登录</div>
              </div>
              <div className={styles.toLoginBtn} onClick={this.toLogin}>
                立即登录
              </div>
            </div>
          ) : //  未登录状态结束
          (!this.state.product) ? (
            // 购物车为空开始
            <div className={styles.cartNotGoods}>
              <div className={styles.notGoodsIcon}>
                <i className={styles.iconStyle + " iconfont icon-gouwuche"}></i>
                <div className={styles.text}>购物车还是空的</div>
              </div>
              <div className={styles.toWatch} onClick={this.toHome}>
                去逛逛
              </div>
            </div>
          ) : (
            //  购物车为空结束
            // 购物车列表开始
            <div className={styles.cartGoodsList}>
              {this.state.data &&
                this.state.data.map((v, i) => {
                  return (
                    <div className={styles.goodsItem} key={v.id}>
                      <div className={styles.icon}>
                        <i
                          className={
                            v.checked
                              ? styles.fontIcon +
                                " iconfont icon-xuanzhong " +
                                styles.choice
                              : styles.fontIcon +
                                " iconfont icon-xuanzhongyuandian"
                          }
                          onClick={this.handlerChoice.bind(this, {
                            checked: v.checked,
                            i,
                          })}
                        ></i>
                      </div>
                      <div className={styles.goodsImg}  onClick={this.handlerToDetail.bind(this,v.idGoods)}>
                        <img src={imgURL + v.goods.pic} alt="" />
                      </div>
                      <div className={styles.goodsContent} onClick={this.handlerToDetail.bind(this,v.idGoods)}>
                        <div className={styles.goodsTitle}>
                          {v.goods.name} {v.sku && v.sku.codeName}
                        </div>
                        <div className={styles.goodsAttr}>
                          {v.goods.descript}
                        </div>
                        <div className={styles.goodsPrice}>
                          ￥
                          <span className={styles.bigPrice}>
                            {v.price / 100}
                          </span>
                          .00
                        </div>
                      </div>
                      <div className={styles.goodsOperate}>
                        <div className={styles.sub}>
                          <i
                            className="iconfont icon-jian"
                            onClick={this.cartSub.bind(this, {
                              id: v.id,
                              count: v.count,
                            })}
                          ></i>
                        </div>
                        <div className={styles.goodsNum}>{v.count}</div>
                        <div className={styles.add}>
                          <i
                            className="iconfont icon-jia"
                            onClick={this.cartAdd.bind(this, {
                              id: v.id,
                              count: v.count,
                            })}
                          ></i>
                        </div>
                      </div>
                    </div>
                  );
                })}
            </div>
          )}
          {/*  购物车列表开始 */}
        </div>
        {/* 购物车内容结束 */}
        {/* 购物车结算开始 */}
        {token && this.state.data && this.state.data.length !== 0 && (
          <div className={styles.cartSettleAccounts}>
            <div className={styles.allChecked}>
              <i
                className={
                  this.state.isChoiceAll
                    ? styles.fontIcon +
                      " iconfont icon-xuanzhong " +
                      styles.choiceAll
                    : styles.fontIcon + " iconfont icon-xuanzhongyuandian"
                }
                onClick={this.handlerChoiceAll}
              ></i>
              <div className={styles.checkText}>全选</div>
            </div>
            <div className={styles.totalPrice}>
              <span className={styles.totalText}>合计：</span>
              <span className={styles.price}>
                ￥<span className={styles.num}>{sum}</span>.00
              </span>
            </div>
            <div className={styles.operateCart}>
              {this.state.isEdit ? (
                <div
                  className={
                    styles.deleteGoods +
                    " " +
                    (this.state.ischecked ? "" : styles.disabled)
                  }
                  onClick={this.deleteGoods}
                >
                  删除{this.state.num ? `(${this.state.num})` : ""}
                </div>
              ) : (
                <div
                  className={
                    styles.settleAccounts +
                    " " +
                    (this.state.ischecked ? "" : styles.disabled)
                  }
                  onClick={this.settleAccounts}
                >
                  结算{this.state.num ? `(${this.state.num})` : ""}
                </div>
              )}
            </div>
          </div>
        )}
        {/* 购物车结算结束 */}
      </div>
    );
  }
}

export default withRouter(Cart);
